<template>
    <el-card>
        <!-- 路径导航 -->
        <div slot="header">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/home' }"> <i class="el-icon-house"></i> 首页</el-breadcrumb-item>
                <el-breadcrumb-item>商品管理</el-breadcrumb-item>
                <el-breadcrumb-item>添加商品</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <!-- 提示信息 -->
         <el-alert
            title="增加商品"
            type="info"
            center
            show-icon>
        </el-alert>
        <!-- 步骤条 -->
        <el-steps :active="activeIndex-0" align-center>
            <el-step title="基本信息"></el-step>
            <el-step title="商品参数"></el-step>
            <el-step title="商品属性"></el-step>
            <el-step title="商品图片"></el-step>
            <el-step title="商品内容"></el-step>
            <el-step title="完成" ></el-step>
        </el-steps>
        <!-- 标签页 -->
        <el-form ref="form" :model="formInfo" :rules="formRules" label-width="150px">
            <el-tabs tab-position="left" :before-leave="beforeLeave" @tab-click="tabClicked" v-model="activeIndex">
                <el-tab-pane label="基本信息" name="0">
                    <el-row>
                        <el-col :span="20" :offset="2">
                            <el-form-item label="商品名称" prop="goods_name">
                                <el-input v-model="formInfo.goods_name" clearable ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="20" :offset="2">
                            <el-form-item label="商品价格" prop="goods_price">
                                <el-input v-model="formInfo.goods_price" type="number" min="0" clearable ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="20" :offset="2">
                            <el-form-item label="商品数量" prop="goods_number">
                                <el-input v-model="formInfo.goods_number" type="number" min="0" clearable ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="20" :offset="2">
                            <el-form-item label="商品重量" prop="goods_weight">
                                <el-input v-model="formInfo.goods_weight" type="number" min="0" clearable ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="20" :offset="2">
                            <el-form-item label="商品分类" prop="goods_cat">
                                <el-cascader :options="cate_list" v-model="formInfo.goods_cat" clearable  :props="{ label:'cat_name',value:'cat_id' }">
                                </el-cascader>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane label="商品参数" name="1">
                     <el-row v-for="item in many_list" :key="item.id">
                        <el-col :span="20" :offset="2">
                            <el-form-item :label="item.attr_name">
                               <el-checkbox-group v-model="item.attr_vals">
                                   <el-checkbox v-for="(val,idx) in item.attr_vals" :key="idx" :label="val"></el-checkbox>
                               </el-checkbox-group>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane label="商品属性" name="2">
                   <el-row v-for="item in only_list" :key="item.id">
                        <el-col :span="20" :offset="2">
                            <el-form-item  :label="item.attr_name">
                               <el-input v-model="item.attr_vals"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name="3">
                    <el-upload
                        class="upload-demo"
                        :action="$baseURL+'upload'"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        :on-success="handleSuccess"
                        :headers="headers"
                        :file-list="fileList"
                        list-type="picture">
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                    <el-dialog title="预览图片" :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-tab-pane>
                <el-tab-pane label="商品内容" name="4">
                    <quill-editor 
                        v-model="formInfo.goods_introduce"
                        ref="myQuillEditor"
                       >
                    </quill-editor>
                    <br>
                    <el-button type="primary" size="default" @click="submitGoods">添加商品</el-button>
                </el-tab-pane>
            </el-tabs>
        </el-form>
    </el-card>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import lodash from 'lodash'

    export default {
        components:{
            quillEditor
        },
        data() {
            return {
                activeIndex: '0', // 激活下标
                formInfo:{  // 表单数据信息
                    goods_name:'1111111',  // 名称
                    goods_cat:[1,3,6],   // 分类ID数组
                    goods_price:'22',  // 价格
                    goods_number:0, // 数量
                    goods_weight:0, // 重量
                    goods_introduce:'', // 商品介绍
                    pics:[], // 图片数组
                    attrs:''  // 动态参数和静态属性 
                },
                formRules:{  // 表单验证规则
                    goods_name:[{required:true,message:'请输入商品名称',trigger:'blur'}],
                    goods_cat:[{required:true,message:'请选择商品分类',trigger:'blur'}],
                    goods_price:[{required:true,message:'请输入商品价格',trigger:'blur'}],
                    goods_number:[{required:true,message:'请输入商品数量',trigger:'blur'}],
                    goods_weight:[{required:true,message:'请输入商品重量',trigger:'blur'}],
                    goods_introduce:[{required:true,message:'请输入商品内容',trigger:'blur'}],
                    pics:[{required:true,message:'请上传图片',trigger:'blur'}]
                },
                cate_list:[],  // 所有商品分类
                only_list:[],   // 商品属性
                many_list:[],   // 商品参数
                fileList:[], // 图片展示数组，回显
                headers:{  // 上传控件的请求头
                    Authorization: (JSON.parse( sessionStorage.getItem('SHOP_USERINFO') )).token
                },
                dialogVisible:false, // 图片预览弹框控制变量
                dialogImageUrl:'', // 预览图片地址
            }
        },
        created () {
            this.getAllCateList()
        },
        computed: {
            // 获取第三级的ID
            cateId() {
                if(this.formInfo.goods_cat.length === 3){
                    return this.formInfo.goods_cat[2]
                }else{
                    return null
                }
            }
        },
        methods: {
            // 获取商品所有分类
            async getAllCateList() {
                let { data:res } = await this.$axios.get('categories')
                if(res.meta.status !==200 ) return this.$message.error(res.meta.msg)
                this.cate_list = res.data
            },
            // tab切换离开事件
            beforeLeave(activeName,oldActiveName){
                // 来自第1个  且   分类ID不存在
                if( !this.cateId && oldActiveName == 0 ){
                    this.$message.error('请选择商品分类')
                    return false
                }
            },
            // tab切换事件
            async tabClicked() {
                let sel = ''
                if(this.activeIndex === '1'){
                    sel = 'many'
                }else if(this.activeIndex === '2'){
                   sel = 'only'
                }else{
                    return
                }
                let { data:res } = await this.$axios.get(`categories/${this.cateId}/attributes`,{
                    params:{ sel }
                })
                if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
                if(sel === 'many'){
                     res.data.forEach(item=>{
                        item.attr_vals = item.attr_vals.length === 0 ? []:item.attr_vals.split(',')
                    })
                }
                this[sel+'_list'] = res.data
            },
            // 图片预览事件
            handlePreview(file){
                this.dialogImageUrl = file.response.data.url
                this.dialogVisible = true
            },
            // 图片移除事件
            handleRemove(file){
                let tmp_path = file.response.data.tmp_path
                // 表单数据中的图片数组中找到对应元素的下标，然后删除他！
                let idx = this.formInfo.pics.findIndex(item=>item.pic=== tmp_path)
                this.formInfo.pics.splice(idx,1)
            },
            // 上传成功
            handleSuccess(response){
                // 把上传成功的路径保存到表单数据里面
                this.formInfo.pics.push({
                    pic:response.data.tmp_path
                })
            },
            // 添加商品提交事件
            submitGoods(){
                this.$refs.form.validate(async valid=>{
                    if(!valid) return
                    // 处理相关数据
                    // 1.表单数据拷贝一份，防止修改数据的时候表单发送异常
                    let deepForm = lodash.cloneDeep(this.formInfo)
                    // 2.处理商品分类
                    deepForm.goods_cat = deepForm.goods_cat.join(",")
                    // 3.处理商品参数
                    let temp_arr = []
                    this.many_list.forEach(item=>{
                        if(item.attr_vals.length){
                            temp_arr.push({
                                attr_id:item.attr_id,
                                attr_value:item.attr_vals.join(",")
                            })
                        }
                    })
                    // 4.处理商品的属性
                    this.only_list.forEach(item=>{
                         if(item.attr_vals.length){
                            temp_arr.push({
                                attr_id:item.attr_id,
                                attr_value:item.attr_vals
                            })
                        }
                    })
                    // 5. 把处理好的静态和动态属性放入到attrs字段中
                    deepForm.attrs = temp_arr
                    // 6.发送数据请求了
                    let { data:res }  = await this.$axios.post('goods',deepForm)
                    if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
                    this.$message.success('添加成功')
                    this.$router.push('/goods')
                })
            }
        },
    }
</script>

<style lang="less" scoped>
.el-steps--horizontal{
    margin-top: 20px;
    margin-bottom: 30px;
}
// deep 选择器是修改组件内部的样式！
/deep/ .ql-editor{
    min-height: 300px;
}

</style>